package com.lanmaoly.web.server.controller;

import com.lanmaoly.web.server.dao.TbOrderItemMapper;
import com.lanmaoly.web.server.dao.TbOrderMapper;
import com.lanmaoly.web.server.entity.PageResult;
import com.lanmaoly.web.server.entity.Result;
import com.lanmaoly.web.server.entity.UserDetailsEntity;
import com.lanmaoly.web.server.pojo.TbOrder;
import com.lanmaoly.web.server.pojo.TbOrderItem;
import com.lanmaoly.web.server.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * controller
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbOrderItemMapper orderItemMapper;

    @RequestMapping("/getOrderInfo")
    public String getOrderInfo(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        if ("anonymousUser".equals(name)) {
            model.addAttribute("isLogin", false);
        } else {
            model.addAttribute("username", authentication.getName());
            model.addAttribute("isLogin", true);
        }
        return "portal/getOrderInfo";
    }

    @RequestMapping("/list")
    public String list(String status, Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        model.addAttribute("username", authentication.getName());
        model.addAttribute("isLogin", true);
        UserDetailsEntity entity = (UserDetailsEntity) authentication.getPrincipal();
        model.addAttribute("headPic", entity.getHeadPic());
        model.addAttribute("status", status);

        List<TbOrder> list = orderMapper.findByUserId(authentication.getName(), status);
        if (list.isEmpty()) {
            model.addAttribute("list", list);
        } else {
            List<Long> longs = list.stream().map(TbOrder::getOrderId).collect(Collectors.toList());
            List<TbOrderItem> items = orderItemMapper.selectByOrderIds(longs);
            Map<Long, List<TbOrderItem>> itemMap = items.stream().collect(Collectors.groupingBy(TbOrderItem::getOrderId));
            for (TbOrder order : list) {
                order.setItemList(itemMap.get(order.getOrderId()));
            }
            model.addAttribute("list", list);
        }
        return "portal/home-index";
    }

    @ResponseBody
    @RequestMapping("/findOne")
    public TbOrder findOne(Long id) {
        return orderService.findOne(id);
    }

    /**
     * $scope.status = ['0', '1未付款', '2交易关闭', '3已付款', '4已发货', '5交易成功', '6确认收货-待评价', '7已评价'];
     *
     * @param tbOrder Order
     * @return Result
     */
    @ResponseBody
    @RequestMapping("/edit/status")
    public Result editStatus( TbOrder tbOrder) {
        String status = tbOrder.getStatus();
        TbOrder order = new TbOrder();
        order.setOrderId(tbOrder.getOrderId());
        order.setStatus(status);
        // 作为更新时间以及交易完成时间
        order.setUpdateTime(new Date());
        if ("2".equals(status)) {
            // 取消订单时间
            order.setCloseTime(order.getUpdateTime());
        } else if ("3".equals(status)) {
            // 付款时间
            order.setPaymentTime(order.getUpdateTime());
        } else if ("4".equals(status)) {
            return Result.fail();
        } else if ("5".equals(status)) {
            return Result.fail();
        } else if ("6".equals(status)) {
            // 确认收货时间
            order.setEndTime(order.getUpdateTime());
        } else if ("7".equals(status)) {
            // 已评价
            order.setBuyerMessage(tbOrder.getBuyerMessage());
            order.setBuyerRate("2");
        } else {
            return Result.fail();
        }
        orderMapper.updateByPrimaryKeySelective(order);
        return Result.success();
    }

    /**
     * 返回全部列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/findAll")
    public List<TbOrder> findAll() {
        return orderService.findAll();
    }


    /**
     * 返回全部列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/findPage")
    public PageResult findPage(int page, int rows) {
        return orderService.findPage(page, rows);
    }

    /**
     * 增加
     *
     * @param order
     * @return
     */
    @ResponseBody
    @RequestMapping("/add")
    public Result add(@RequestBody TbOrder order) {
        //获取当前登录人账号
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        order.setUserId(authentication.getName());
        UserDetailsEntity entity = (UserDetailsEntity) authentication.getPrincipal();
        order.setSourceType("2");
        order.setBuyerNick(entity.getNickName());
        //订单来源  PC
        try {
            orderService.add(order);
            return new Result(true, "增加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "增加失败");
        }
    }

    /**
     * 修改
     *
     * @param order
     * @return
     */
    @ResponseBody
    @RequestMapping("/update")
    public Result update(@RequestBody TbOrder order) {
        try {
            orderService.update(order);
            return new Result(true, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("/delete")
    public Result delete(Long[] ids) {
        try {
            orderService.delete(ids);
            return new Result(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }

    /**
     * 查询+分页
     *
     * @param page
     * @param rows
     * @return
     */
    @ResponseBody
    @RequestMapping("/search")
    public PageResult search(@RequestBody TbOrder order, int page, int rows) {
        return orderService.findPage(order, page, rows);
    }

}
